import holidays
from datetime import datetime, timedelta

# 获取上一个交易日日期字符串
def get_previous_trading_day_auto(date_str, country='CN') -> str:
    """
    :param date_str: 日期字符串 格式为 %Y%m%d
    :param country: 国家代码 默认为 CN
    :return: 上一个交易日日期字符串 格式为 %Y%m%d
    """
    us_holidays = holidays.country_holidays(country)
    date = datetime.strptime(date_str, '%Y%m%d')

    while True:
        date -= timedelta(days=1)
        if date.weekday() >= 5:
            continue
        if date in us_holidays:
            continue
        break
    return date.strftime('%Y%m%d')


# 使用示例
previous_trading_day = get_previous_trading_day_auto('20250324', country='CN')
print(previous_trading_day)
